package com.ruoyi.livesass.api.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyl.manager.lbs.domain.LbsZbjl;
import com.cyl.manager.lbs.service.LbsZbjlService;
import com.google.common.collect.Maps;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.livesass.LiveVideoService;
import com.ruoyi.livesass.api.domain.LbsZbrqsj;
import com.ruoyi.livesass.api.mapper.LbsZbrqsjMapper;
import com.ruoyi.livesass.api.service.LbsZbrqsjService;
import com.ruoyi.livesass.api.sync.LiveTrafficDataSynService;
import com.volcengine.model.livesaas.response.AnalysisUserBehaviorPeopleV2Response;
import com.volcengine.model.livesaas.response.AnalysisUserBehaviorPeopleV2Response.AnalysisUserBehaviorPeopleV2Body;
import com.volcengine.model.livesaas.response.GetActivityAPIResponse;
import com.volcengine.model.livesaas.response.GetActivityAPIResponse.GetActivityAPIBody;
import com.volcengine.model.livesaas.response.GetAdvertisementDataDetailAPIResponse;
import com.volcengine.model.livesaas.response.GetPageWatchDataAPIV2Response.PageClicksFormAPI;
import com.volcengine.model.livesaas.response.GetRealTimeOnlineNumberAPIResponse;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.ApiOperation;


/**
* @ClassName: ZbjDpDataController 
* @Description: TODO(直播间大屏数据获取接口) 
* @author 晏大兵 
* @date 2025年3月10日 下午3:02:46 
 */
@RestController
@RequestMapping("/api/zbjdp")
public class ZbjDpDataController extends BaseController {
	
	private static final Logger LOG = LoggerFactory.getLogger(LiveTrafficDataSynService.class);
	
    @Autowired
    private LbsZbrqsjMapper lbsZbrqsjMapper;
	
    @Autowired
    private LbsZbrqsjService service;
	
	@Autowired
	LiveVideoService liveVideoService;
	
	@Autowired
	LbsZbjlService lbsZbjlService;
	
	@Autowired
	RedisCache redisCache;
	
	String hsCacheKey = "hsData";
	
	
    @ApiOperation("查询直播实时数据无延迟")
    @PreAuthorize("@ss.hasPermi('lbs:lbsZbjl:bigscreen')")
    @PostMapping("/liveNowData")
    public ResponseEntity<LbsZbrqsj> liveNowData(long zbjid) throws Exception {
    	
    	
    	//TODO 这里增加缓存调用
    	String cacheKey = hsCacheKey + "_liveNowData_" + zbjid;
    	
    	if(redisCache.hasKey(cacheKey)) {
    		try {
    			LbsZbrqsj lbsZbrqsj  = redisCache.getCacheObject(cacheKey);
        		return ResponseEntity.ok(lbsZbrqsj);
    		}catch(Exception e) {
    			e.printStackTrace();
    			LOG.error("liveNowData读取缓存出错 | " + e.getMessage());
    		}
    		
    	};
    	
    	
    	LbsZbrqsj lbsZbrqsj = new LbsZbrqsj();
    	
    	PageClicksFormAPI pageClicksFormAPI = liveVideoService.getPageWatchData(zbjid);
    	lbsZbrqsj.setAvgNumber(new BigDecimal(pageClicksFormAPI.getAvgNumber()));
    	lbsZbrqsj.setAvgTime(new BigDecimal(pageClicksFormAPI.getAvgTime()));
    	lbsZbrqsj.setTotalTime(pageClicksFormAPI.getTotalTime().intValue());
    	lbsZbrqsj.setPv(pageClicksFormAPI.getPV().intValue());
    	lbsZbrqsj.setUv(pageClicksFormAPI.getUV().intValue());
    	lbsZbrqsj.setPcu(pageClicksFormAPI.getPCU().intValue());
    	
    	
    	GetRealTimeOnlineNumberAPIResponse getRealTimeOnlineNumberAPIResponse = liveVideoService.getRealTimeOnlineNumber(zbjid);
    	
    	lbsZbrqsj.setZsrs(getRealTimeOnlineNumberAPIResponse.getResult().getRealPopularity().intValue());
    	lbsZbrqsj.setXnrs(getRealTimeOnlineNumberAPIResponse.getResult().getFakePopularity().intValue());
    	
    	
    	redisCache.setCacheObject(cacheKey , lbsZbrqsj, 3, TimeUnit.SECONDS);
    	
    	
        return ResponseEntity.ok(lbsZbrqsj);
    }
    
    
	
	
    @ApiOperation("查询直播间真实开播时间和结束时间")
    @PreAuthorize("@ss.hasPermi('lbs:lbsZbjl:bigscreen')")
    @PostMapping("/liveStartAndEnd")
    public ResponseEntity<Map<String, String>> liveStartAndEnd(long zbjid) throws Exception {
    	Map<String, String> resultMpa = Maps.newHashMap();
    	LbsZbjl lbsZbjl = lbsZbjlService.selectById(zbjid);
    	
    	if(null != lbsZbjl) {
    		 //使用系统创建的计划开始时间-防止提前推流导致前面数据都为空
    		
    		if(StrUtil.isBlankIfStr(lbsZbjl.getZsjssj())) { //没有收到结束回调，通过火山再次确认是否结束直播
    			GetActivityAPIResponse response = liveVideoService.getActivityInfo(zbjid);
    			if(null != response && null != response.getResult()) { //使用系统创建的计划开始时间-防止提前推流导致前面数据都为空
    				GetActivityAPIBody activityInfo = response.getResult();
    				//resultMpa.put("zbzt",  "" + activityInfo.getStatus() ); 
    				
    				if(activityInfo.getStatus() == 2) { //直播还处于预告中直接返回空数据
    					return ResponseEntity.ok(resultMpa);
    				}
    				
    				if(activityInfo.getStatus() == 4) { //直播结束
    					Long endTime = response.getResult().getEndTime();
            			if(endTime != 0 ) {
            				resultMpa.put("endTime",  DateTime.of( (endTime * 1000) ).toDateStr() );
            			}else {
            				resultMpa.put("endTime",  lbsZbjl.getJhjssj() );
            			}
    				}
    				
        		}
    		}else {
    			//直接使用回调时产生的真实结束时间
    			resultMpa.put("endTime",  lbsZbjl.getZsjssj() );
    		}
    		
    		if(!StrUtil.isBlankIfStr(lbsZbjl.getZskssj()))  {
    			resultMpa.put("startTime",  lbsZbjl.getZskssj() );
    		}else {
    			resultMpa.put("startTime",  lbsZbjl.getJhkssj() );
    		}
    		
    	}
    	
    	return ResponseEntity.ok(resultMpa);
    }
	
	
    @ApiOperation("查询直播观看时长-当前直播间根据颗粒度返回  超过10分钟 超过20分钟 超过30分钟 超过40分钟 超过50分钟 超过60分钟")
    @PreAuthorize("@ss.hasPermi('lbs:lbsZbjl:bigscreen')")
    @PostMapping("/liveTime")
    public ResponseEntity<Map<String,AnalysisUserBehaviorPeopleV2Body>> liveTime(long zbjid) throws Exception {
    	
    	Map<String,AnalysisUserBehaviorPeopleV2Body> resultData = Maps.newHashMap();
    	try {
    		
	    	//TODO 这里增加缓存调用
	    	String cacheKey = hsCacheKey + "_liveTime_" + zbjid;
	    	
	    	if(redisCache.hasKey(cacheKey)) {
	    		try {
	    			Map<String,AnalysisUserBehaviorPeopleV2Body> resultDataCache  = redisCache.getCacheObject(cacheKey);
		    		return ResponseEntity.ok(resultDataCache);
	    		}catch(Exception e) {
	    			e.printStackTrace();
	    			LOG.error("liveTime读取缓存出错 | " + e.getMessage());
	    		}
	    	};
	    	
	   		
	    	
	    	
    		
    		/*
    		//观看时间大于0分钟的
        	resultData.put("010m", processInterval(zbjid, 0, 10));
        	//观看时间大于10分钟的
        	resultData.put("1020m", processInterval(zbjid, 10, 20));
        	//观看时间大于20分钟的
        	resultData.put("2030m", processInterval(zbjid, 20, 30));
        	//观看时间大于30分钟的
        	resultData.put("3060m", processInterval(zbjid, 30, 60));
        	//观看时间大于40分钟的
        	resultData.put("60m", processInterval(zbjid, 60, -1));
        	*/
    		
    		//观看时间大于0分钟的
        	resultData.put("010m", processInterval(zbjid, 1));
        	//观看时间大于10分钟的
        	resultData.put("1020m", processInterval(zbjid, 10));
        	//观看时间大于20分钟的
        	resultData.put("2030m", processInterval(zbjid, 20));
        	//观看时间大于30分钟的
        	resultData.put("3060m", processInterval(zbjid, 30));
        	//观看时间大于40分钟的
        	resultData.put("60m", processInterval(zbjid, 60));
    		
        	
        	redisCache.setCacheObject(cacheKey , resultData, 3, TimeUnit.SECONDS);
    		
            return ResponseEntity.ok(resultData);
    	}catch(Exception e) {
    		e.printStackTrace();
    	}
    	return ResponseEntity.ok(resultData);
    }
    

    @ApiOperation("查询直播实时数据|    AvgNumber-平均在线人数,AvgTime-平均观看时长,PCU-最高在线人数,PV-总观看人次,TotalTime-总观看时长(所有人合并后的时长),UV-总观看人数（相同设备合并后的数据）,ZSRS-真实人数,XNRS-虚拟人数")
    @PreAuthorize("@ss.hasPermi('lbs:lbsZbjl:bigscreen')")
    @PostMapping("/liveData")
    public ResponseEntity<List<LbsZbrqsj>> liveData(long zbjid, String startTime, String endTime) throws Exception {

    	QueryWrapper<LbsZbrqsj> query = new QueryWrapper<>();
        query.eq("activity_id", zbjid);
        query.ge("cssj", startTime);
        query.le("cssj", endTime);
        query.orderByDesc("create_time");
        
    	List<LbsZbrqsj> resutlList = lbsZbrqsjMapper.selectList(query);
    	
        return ResponseEntity.ok(resutlList);
    }
    
    /**/
    @ApiOperation("商品卡片点击次数")
    @PreAuthorize("@ss.hasPermi('lbs:lbsZbjl:bigscreen')")
    @PostMapping("/popClickCount")
    public ResponseEntity<Integer> popClickCount(long zbjid) throws Exception {
	    try {
	    	
	    	//TODO 这里增加缓存调用
	    	String cacheKey = hsCacheKey + "_popClickCount_" + zbjid;
	    	if(redisCache.hasKey(cacheKey)) {
	    		
	    		try {
		    		Integer totalCount = redisCache.getCacheObject(cacheKey);
		    		return ResponseEntity.ok(totalCount);
	    		}catch(Exception e) {
	    			e.printStackTrace();
	    			LOG.error("popClickCount读取缓存出错 | " + e.getMessage());
	    		}
	    		
	    		

	    	};
	    	
	    	GetAdvertisementDataDetailAPIResponse response = liveVideoService.getAdvertisementData(zbjid);
	    	Integer totalCount = response.getResult().getTotalCount();
	    	
	    	redisCache.setCacheObject(cacheKey , totalCount, 3, TimeUnit.SECONDS);
	    	
	        return ResponseEntity.ok(totalCount);
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseEntity.ok(0);
		}		
    }
    
    

    /**
    * @Title: processInterval 
    * @Description: TODO(根据观看百分比以及总时间来过滤观看时长的人数) 
    * @param @return
    * @param @throws Exception    设定文件 
    * @return AnalysisUserBehaviorPeopleV2Body    返回类型 
    * @throws
     */
    private AnalysisUserBehaviorPeopleV2Body processInterval(long zbjid, int intervalStart, int intervalEnd) throws Exception {
    	/**/
    	//获取直播间信息
    	GetActivityAPIResponse activityAPIResponse = liveVideoService.getActivityInfo(zbjid);
    	long liveTime = activityAPIResponse.getResult().getLiveTime(); //直播开始时间
    	long startTime = liveTime + (intervalStart * 60) ;
    	long endTime = liveTime + (intervalEnd * 60) ;
    	
    	AnalysisUserBehaviorPeopleV2Response response = liveVideoService.getAnalysisUserBehaviorPeople(zbjid, startTime, endTime);
    	return response.getResult();
    }
    
    
    
    /**
    * @Title: processInterval 
    * @Description: TODO(根据观看百分比以及总时间来过滤观看时长的人数) 
    * @param @return
    * @param @throws Exception    设定文件 
    * @return AnalysisUserBehaviorPeopleV2Body    返回类型 
    * @throws
     */
    private AnalysisUserBehaviorPeopleV2Body processInterval(long zbjid, int bfb) throws Exception {
    	AnalysisUserBehaviorPeopleV2Response response = liveVideoService.getAnalysisUserBehaviorPeople(zbjid, bfb);
    	return response.getResult();
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    


}
